package service

import (
	"context"
	"fmt"
	"io"
	"math/rand/v2"
	"time"

	pb "helloworld/api/helloworld/v1"
	"helloworld/internal/data"
)

type AuthService struct {
	pb.UnimplementedAuthServer
	data *data.Data
}

func NewAuthService(
	data *data.Data,
) pb.AuthServer {
	return &AuthService{data: data}
}

func (s *AuthService) Single(ctx context.Context, req *pb.LoginRequest) (*pb.LoginResponse, error) {
	return &pb.LoginResponse{
		AccessToken: "Single",
		ExpiresIn:   rand.Int32N(100),
	}, nil
}
func (s *AuthService) RespStream(req *pb.LoginRequest, conn pb.Auth_RespStreamServer) error {
	fmt.Println("RespStream", req)
	for {
		err := conn.Send(&pb.LoginResponse{})
		if err != nil {
			return err
		}
		time.Sleep(200 * time.Millisecond)
	}
}
func (s *AuthService) ReqStream(conn pb.Auth_ReqStreamServer) error {
	for {
		req, err := conn.Recv()
		if err == io.EOF {
			return conn.SendAndClose(&pb.LoginResponse{
				AccessToken: "END",
				ExpiresIn:   120,
			})
		}
		if err != nil {
			return err
		}
		fmt.Println("req:", req)
		time.Sleep(200 * time.Millisecond)
	}
}
func (s *AuthService) Stream(conn pb.Auth_StreamServer) error {
	for {
		req, err := conn.Recv()
		if err == io.EOF {
			return conn.SendAndClose(&pb.LoginResponse{
				AccessToken: "",
				ExpiresIn:   0,
			})
		}
		if err != nil {
			return err
		}
		fmt.Println("req:", req)
		time.Sleep(200 * time.Millisecond)
	}
}
func (s *AuthService) SayHello(ctx context.Context, req *pb.LoginRequest) (*pb.LoginResponse, error) {
	return &pb.LoginResponse{
		AccessToken: req.Code,
		ExpiresIn:   0,
	}, nil
}
